package hello.app.util;

import android.R;
import android.content.Context;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.view.Display;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.AlphaAnimation;
import android.view.animation.AnimationSet;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import hello.app.model.HelloSetting;

import java.util.Timer;
import java.util.TimerTask;



/**
 * 自作トースト<br>
 * 表示する時間を指定しない場合cancelを呼ぶまで表示し続けるので注意
 * @param context
 */
public class AdteToast {
	private WindowManager mWindowManager;
	private CancelListener cancelListener;
	private RelativeLayout mLayout;
	private Context mContext;
	private ImageView mImageView;
	private static AdteToast instance;
	private Timer mTimer;
	public static final int HIGH = 0;
	public static final int LITTLE_HIGH = 1;
	public static final int CENTER = 2;
	public static final int LITTLE_LOW = 3;
	public static final int LOW = 4;
	private static final int MAX_LINE = 12;

	public interface CancelListener{
		public void onCancel();
	}
	/**
	 * 表示する場所
	 * @author Tamanyan
	 *
	 */
	public enum Position{
		HIGH,
		LITTLE_HIGH,
		CENTER,
		LITTLE_LOW,
		LOW
	}

	public class CencelTask extends TimerTask {
		private AdteToast toast;
		public CencelTask(AdteToast toast){
			this.toast = toast;
		}
		public void run() {
			toast.cancel();
		}
	}

	private AdteToast(Context context) {
		mWindowManager = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
        this.mContext = context;
        mTimer = new Timer();
	}

	/**
	 * トーストのインスタンスを取得する
	 * @param context
	 */
	public static AdteToast getInstance(Context context){
		// トーストをあちこち作成すると消えないトーストが出てくるのでシングルトンで管理する
		if(instance == null){
			instance = new AdteToast(context);
		}
		return instance;
	}

	private TextView getTextView(){
		TextView textView  = new TextView(mContext);
		//LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT);
		//textView.setText("HOGEHOGE");
		textView.setTextAppearance(mContext, android.R.attr.textAppearanceLarge);
		textView.setTextSize(12.0f);
		textView.setTextColor(Color.WHITE);
		textView.setBackgroundColor(Color.argb(240, 100, 100, 100));
		textView.setPadding(10, 5, 10, 5);

		AlphaAnimation fadein = new AlphaAnimation(0.0f,1.0f);
		fadein.setInterpolator(new AccelerateInterpolator());
		fadein.setDuration(500);

		AnimationSet set = new AnimationSet(false);
		set.setFillEnabled(true);
		set.setFillAfter(true);
		set.addAnimation(fadein);
		//set.addAnimation(fadeout);
		textView.startAnimation(set);

		return textView;
	}

	private ImageView getCrossMarkImageView(){
		ImageView imageView  = new ImageView(mContext);
		imageView.setImageResource(hello.app.R.drawable.nomark001);
		AlphaAnimation fadein = new AlphaAnimation(0.0f,1.0f);
		fadein.setInterpolator(new AccelerateInterpolator());
		fadein.setDuration(500);

		AnimationSet set = new AnimationSet(false);
		set.setFillEnabled(true);
		set.setFillAfter(true);
		set.addAnimation(fadein);
		//set.addAnimation(fadeout);
		imageView.startAnimation(set);
		imageView.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				cancel();
			}
		});
		return imageView;
	}

	//比は1.6の時に丁度いいように調整してある
	private int getHeightLineByProportion(float p, float fontsize){
		fontsize *= (1.6666666f / p) * 1.15;
		return (int)fontsize;
	}


	/**
	 * トーストを表示する
	 * @param msg
	 * 表示するメッセージ
	 * @param pos
	 * 表示する場所
	 * @param time
	 * 表示する時間ミリセカンド
	 */
	public void show(String msg, Position pos, int time){
		this.show(msg, pos);
		mTimer.schedule(new CencelTask(this), time);	//キャンセルタスクを仕込む
	}

	/**
	 *　トーストを表示する
	 * @param msg
	 * 表示するメッセージ
	 * @param pos
	 * 表示する場所
	 * @param time
	 * 表示する時間ミリセカンド
	 */
	public void show(String msg, int pos_id, int time){
		this.show(msg, pos_id);
		mTimer.schedule(new CencelTask(this), time);	//キャンセルタスクを仕込む
	}

	/**
	 *　トーストを表示する
	 * @param msg
	 * 表示するメッセージ
	 * @param pos
	 * 表示する場所
	 */
	public synchronized void show(String msg, Position pos){
		if(pos == Position.HIGH){
			show(msg, HIGH);
		}else if(pos == Position.LITTLE_HIGH){
			show(msg, LITTLE_HIGH);
		}else if(pos == Position.CENTER){
			show(msg, CENTER);
		}else if(pos == Position.LITTLE_LOW){
			show(msg, LITTLE_LOW);
		}else if(pos == Position.LOW){
			show(msg, LOW);
		}else{
			show(msg, CENTER);
		}
	}

	/**　
	 *　トーストを表示する
	 * @param msg
	 * 表示するメッセージ
	 * @param pos
	 * 表示する場所
	 */
	public synchronized void show(String msg, int pos){
		cancel();
		mLayout = new RelativeLayout(mContext);
		LinearLayout linear = new LinearLayout(mContext);
		linear.setOrientation(LinearLayout.VERTICAL);
		ScrollView scrollView = new ScrollView(mContext);
		TextView textView = getTextView();
		mImageView = getCrossMarkImageView();
		textView.setText(msg);
		Display display = mWindowManager.getDefaultDisplay();
		float p = (float)display.getHeight() / (float)display.getWidth();

		int height = 20 + (int)(textView.getTextSize()*2.0f) + Util.countChar(msg, '\n') * getHeightLineByProportion(p,textView.getTextSize());	//行の分だけ
		if(Util.countChar(msg, '\n') > MAX_LINE){
			height = 20 + (int)(textView.getTextSize()*2.0f) + MAX_LINE * getHeightLineByProportion(p,textView.getTextSize());	//行の分だけ
		}
		int y;
		if(pos == HIGH){
			y =  HelloSetting.DISPLAY_POSTION[HIGH];
		}else if(pos == LITTLE_HIGH){
			y = HelloSetting.DISPLAY_POSTION[LITTLE_HIGH];
		}else if(pos == CENTER){
			y = HelloSetting.DISPLAY_POSTION[CENTER];
		}else if(pos == LITTLE_LOW){
			y = HelloSetting.DISPLAY_POSTION[LITTLE_LOW];
		}else if(pos == LOW){
			y = HelloSetting.DISPLAY_POSTION[LOW];
		}else{
			y = display.getHeight() / 2;
		}
		RelativeLayout.LayoutParams l = new RelativeLayout.LayoutParams((int)(display.getWidth()*0.9), height);
		l.setMargins((int)(display.getWidth() * 0.05), 0, 0, 0);

		WindowManager.LayoutParams params = new WindowManager.LayoutParams(
				display.getWidth(),
				height,
                WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,
                WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH |
                WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR |
                WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN |
                WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL,
                PixelFormat.TRANSLUCENT);
		params.gravity = Gravity.CENTER;
		params.y = y;

		linear.addView(textView);
		scrollView.addView(linear);
		mLayout.addView(scrollView, l);

		mWindowManager.addView(mLayout, params);
		params = new WindowManager.LayoutParams(
				display.getWidth()/6,
				display.getWidth()/6,
                WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,
                WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH |
                WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR |
                WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN |
                WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL,
                PixelFormat.TRANSLUCENT);
		params.gravity = Gravity.RIGHT;
		params.y = y - height / 2;

		mWindowManager.addView(mImageView, params);
	}

	/**
	 * トーストを消す
	 */
	public synchronized void cancel(){
		if(mImageView != null){
			mWindowManager.removeView(mImageView);
			mImageView = null;
		}
		if(mLayout != null){
			mWindowManager.removeView(mLayout);
			if(cancelListener != null){
				cancelListener.onCancel();
			}
			mLayout = null;
		}
	}

	public void setCancelListener(CancelListener cancelListener) {
		this.cancelListener = cancelListener;
	}
}
